package com.myapp.web.servlet.upload;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUploadServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1120589255802702328L;

	private static Log log = LogFactory.getLog(FileUploadServlet.class);
	
	private static final long MAX_LENGTH = 10 * 1024 * 1024L; // 10MB
	
	private static final int HTTP_REDUNDANT_LENGTH = 1024; // 1KB
	
	protected String localFileName = null;

	private static final String FILE_UPLOAD_JSP = "/pages/admin/fileUplod.jsp";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher rd = request.getRequestDispatcher(FILE_UPLOAD_JSP);
		rd.forward(request, response);
	}
	
	protected void preUploadProcess(HttpServletRequest request,HttpServletResponse response)
	{
		
	}
	
	protected void postUploadProcess(HttpServletRequest request,HttpServletResponse response)
	{
		
	}
	
	protected void doPost(HttpServletRequest request,HttpServletResponse response)
	    throws ServletException,IOException {

		ProgressInfo pi = new ProgressInfo();
		
		try {
			preUploadProcess(request,response);			
			this.doUpload(request,pi);
			postUploadProcess(request,response);		
		} catch (Exception e) {
			pi.setInProgress(false);
			log.info("cancelled or interrupted!");
			e.printStackTrace();
			throw new ServletException(e);
		}
	}
	protected String getFileName()
	{
		return "abb";
	}
	
	private void doUpload(HttpServletRequest request, ProgressInfo pi) throws Exception{
		String fldName = "";
		FileItemStream item = null;
		BufferedInputStream stream = null;
		boolean isExceeded = false;

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		if (isMultipart) {
			int filesSize = request.getContentLength() - HTTP_REDUNDANT_LENGTH;
			
			ServletFileUpload upload = new ServletFileUpload();
			upload.setHeaderEncoding("UTF-8");
			upload.setFileSizeMax(MAX_LENGTH);
			upload.setSizeMax(MAX_LENGTH);
			
			if (filesSize >= MAX_LENGTH) {
				String errorMsg = "Error: Current files size is " + filesSize
						/ (1024 * 1024) + "MB which has exceeded max " + "10MB";
				pi.setCompleted(true);
				pi.setErrorMsg(errorMsg);
				isExceeded = true;
			}			
			UploadProgressListener uploadListener = new UploadProgressListener(pi);
			uploadListener.setActiveReverseAjax(true);
			upload.setProgressListener(uploadListener);
			
			if(isExceeded == true){
				if(log.isDebugEnabled()){
					log.info("文件上传超出了大小");
				}
				return ;
			}
			
			// Parse the request
			FileItemIterator fIter = upload.getItemIterator(request);
			
			while (fIter.hasNext()) {
				item = fIter.next();
				fldName = item.getFieldName();
				if(log.isDebugEnabled()){
					log.info(fldName + "," + item.isFormField() + ", " + item.getContentType()
							+ ", " + item.getName() + ", " + item.getHeaders());
				}				

				if (!item.isFormField()) {
					fldName = item.getFieldName();
					if (item.getName() == null
							|| "".equals(item.getName().trim())) {
						continue;
					}
					setLocalFileName(item.getName());
					pi.setCurFileName(item.getName());
					pi.setUploadedFiles(pi.getUploadedFiles() + "<b>"+item.getName() + "</b><br/>");
					
					stream = new BufferedInputStream(item.openStream());
					ByteArrayOutputStream bStream = new ByteArrayOutputStream();
					long bStreamLen = Streams.copy(stream, bStream, true);

					if(log.isDebugEnabled()){
						log.info("FileUploadServlet:"+getFileName());
					}
				
					File file = new File(getFileName());					
					try {
						if (file.exists()) {
							boolean idDeleted = file.delete();
							if(!idDeleted){
								log.info("删除文件不成功");
							}
						}
						OutputStream out = new FileOutputStream(file);
						bStream.writeTo(out);
						bStream.close();
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(log.isDebugEnabled()){
						log.info(fldName+ " just was uploaded, len " + bStreamLen);	
					}									
				}
			}
		}
	}

	private void setLocalFileName(String localFileName) {
		this.localFileName = localFileName;
	}	
}
